import torch
import torch.nn as nn
import torch.nn.functional as F

import torch
import torch.nn as nn
from typing import Dict, List



def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, groups=groups, bias=False, dilation=dilation)


def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


class Bottleneck(nn.Module):
    # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
    # while original implementation places the stride at the first 1x1 convolution(self.conv1)
    # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
    # This variant is also known as ResNet V1.5 and improves accuracy according to
    # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.

    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out
class Convblock(nn.Module):
    def __init__(self,in_channels,out_channels,k_size=3,str=1,pad=1):
        super(Convblock, self).__init__()
        self.conv_bn_relu=nn.Sequential(
            nn.Conv2d(in_channels,out_channels,kernel_size=k_size,stride=str,padding=pad),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
        )
    def forward(self,x):
        # print(x.shape)
        x=self.conv_bn_relu(x)
        return x

class Fconvblock(nn.Module):
    def __init__(self,in_channels,out_channels,k_size=3,str=2,pad=1,out_pad=1):
        super(Fconvblock, self).__init__()
        self.deconv=nn.ConvTranspose2d(in_channels,out_channels,kernel_size=k_size,stride=str, padding=pad,output_padding=out_pad)
        self.bn=nn.BatchNorm2d(out_channels)

    def forward(self,x,is_act=True):
        x=self.deconv(x)
        if is_act:
            x=torch.relu(self.bn(x))
        return x


class EncodeBLk(nn.Module):
    def __init__(self,in_channels,out_channels):
        super(EncodeBLk, self).__init__()
        self.conv1=Convblock(in_channels,out_channels,str=2)
        self.conv2=Convblock(out_channels,out_channels)

        self.conv3=Convblock(out_channels,out_channels)
        self.conv4 = Convblock(out_channels, out_channels)

        self.shortcut=Convblock(in_channels,out_channels,str=2)

    def forward(self,input):
        x=self.conv1(input)
        x=self.conv2(x)

        shortcut=self.shortcut(input)

        x=x+shortcut

        z=self.conv3(x)
        z=self.conv4(x)

        z=z+x
        return x

class EncodeBLkshort(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(EncodeBLkshort, self).__init__()
        self.conv1 = Convblock(in_channels, out_channels, str=2)

        self.norm = nn.LayerNorm(out_channels)
        self.relu = nn.LeakyReLU()

    def forward(self, input):
        x = self.conv1(input)
        x = x.permute(0, 2, 3, 1)
        x = self.norm(x)
        x = self.relu(x)
        x=x.permute(0,3,1,2)

        return x
class ASPPConv(nn.Sequential):
    def __init__(self, in_channels: int, out_channels: int, dilation: int) -> None:
        super(ASPPConv, self).__init__(
            nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU()
        )


class ASPPPooling(nn.Sequential):
    def __init__(self, in_channels: int, out_channels: int) -> None:
        super(ASPPPooling, self).__init__(
            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(in_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU()
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        size = x.shape[-2:]
        for mod in self:
            x = mod(x)
        return F.interpolate(x, size=size, mode='bilinear', align_corners=False)

class ASPP(nn.Module):
    def __init__(self, in_channels: int, atrous_rates: List[int], out_channels: int = 768) -> None:
        super(ASPP, self).__init__()
        modules = [
            nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
                          nn.BatchNorm2d(out_channels),
                          nn.ReLU())
        ]

        rates = tuple(atrous_rates)
        for rate in rates:
            modules.append(ASPPConv(in_channels, out_channels, rate))

        modules.append(ASPPPooling(in_channels, out_channels))

        self.convs = nn.ModuleList(modules)

        self.project = nn.Sequential(
            nn.Conv2d(len(self.convs) * out_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
            nn.Dropout(0.5)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        _res = []
        for conv in self.convs:
            _res.append(conv(x))
        res = torch.cat(_res, dim=1)
        return self.project(res)

class DecodeBLK(nn.Module):
    def __init__(self,in_channels,out_channels):
        super(DecodeBLK, self).__init__()
        self.conv1=Convblock(in_channels,in_channels//4,k_size=1,pad=0)
        self.dconv=Fconvblock(in_channels//4,in_channels//4)
        self.conv2=Convblock(in_channels//4,out_channels,k_size=1,pad=0)

    def forward(self,x):
        x=self.conv1(x)
        x=self.dconv(x)
        x=self.conv2(x)
        return x
class VGG16(nn.Module):

    def __init__(self):
        super(VGG16, self).__init__()

        # 3 * 224 * 224
        self.conv1_1 = nn.Conv2d(3, 64, 3,padding=(1, 1))  # 64 * 222 * 222
        self.conv1_2 = nn.Conv2d(64, 64, 3, padding=(1, 1))  # 64 * 222* 222
        self.maxpool1 = nn.MaxPool2d((2, 2))  # pooling 64 * 112 * 112

        self.conv2_1 = nn.Conv2d(64, 128, 3,padding=(1, 1))  # 128 * 110 * 110
        self.conv2_2 = nn.Conv2d(128, 128, 3, padding=(1, 1))  # 128 * 110 * 110
        self.maxpool2 = nn.MaxPool2d((2, 2))  # pooling 128 * 56 * 56

        self.conv3_1 = nn.Conv2d(128, 256, 3,padding=(1, 1))  # 256 * 54 * 54
        self.conv3_2 = nn.Conv2d(256, 256, 3, padding=(1, 1))  # 256 * 54 * 54
        self.conv3_3 = nn.Conv2d(256, 256, 3, padding=(1, 1))  # 256 * 54 * 54
        # self.conv3_4 = nn.Conv2d(256, 256, 3, padding=(1, 1))
        self.maxpool3 = nn.MaxPool2d((2, 2))  # pooling 256 * 28 * 28

        self.conv4_1 = nn.Conv2d(256, 512, 3,padding=(1, 1))  # 512 * 26 * 26
        self.conv4_2 = nn.Conv2d(512, 512, 3, padding=(1, 1))  # 512 * 26 * 26
        self.conv4_3 = nn.Conv2d(512, 512, 3, padding=(1, 1))  # 512 * 26 * 26
        # self.conv4_4 = nn.Conv2d(512, 512, 3, padding=(1, 1))
        self.maxpool4 = nn.MaxPool2d((2, 2))  # pooling 512 * 14 * 14

        self.conv5_1 = nn.Conv2d(512, 512, 3,padding=(1, 1))  # 512 * 12 * 12
        self.conv5_2 = nn.Conv2d(512, 512, 3, padding=(1, 1))  # 512 * 12 * 12
        self.conv5_3 = nn.Conv2d(512, 512, 3, padding=(1, 1))  # 512 * 12 * 12
        # self.conv5_4 = nn.Conv2d(512, 512, 3, padding=(1, 1))
        self.maxpool5 = nn.MaxPool2d((2, 2))  # pooling 512 * 7 * 7
        self.ASPP=ASPP(512, [12, 24, 36])

        self.encon1 = EncodeBLkshort(128, 96)
        self.encon2 = EncodeBLkshort(256, 192)
        self.encon3 = EncodeBLkshort(512, 384)


        self.Debl4 = DecodeBLK(768, 384)
        self.Debl3 = DecodeBLK(384, 192)
        self.Debl2 = DecodeBLK(192, 96)

        self.decov1 = Fconvblock(96, 32)
        self.conv2 = Convblock(32, 32)
        self.decov2 = Fconvblock(32, 2, k_size=2, pad=0, out_pad=0)


        # softmax 1 * 1 * 1000

    def forward(self, x):
        # x.size(0)即为batch_size
        in_size = x.size(0)

        out = self.conv1_1(x)  # 224
        out = F.relu(out)
        out = self.conv1_2(out)  # 224
        out = F.relu(out)
        out = self.maxpool1(out)  # 112*112*64

        out = self.conv2_1(out)  #
        out = F.relu(out)
        out = self.conv2_2(out)  # 112*112*128
        out2 = F.relu(out)
        out = self.maxpool2(out2)  # 56*56*128

        out = self.conv3_1(out)
        out = F.relu(out)
        out = self.conv3_2(out)
        out = F.relu(out)
        out = self.conv3_3(out)  # 56*56*256
        out3 = F.relu(out)
        # out = self.conv3_4(out)  # 56*56*256
        # out3 = F.relu(out)
        out = self.maxpool3(out3)  # 28*28*256

        out = self.conv4_1(out)  # 26
        out = F.relu(out)
        out = self.conv4_2(out)  # 26
        out = F.relu(out)
        out = self.conv4_3(out)  # 28*28*512
        out4 = F.relu(out)
        # out = self.conv4_4(out)  # 28*28*512
        # out4 = F.relu(out)
        out = self.maxpool4(out4)  # 14*14*512

        out = self.conv5_1(out)  # 12
        out = F.relu(out)
        out = self.conv5_2(out)  # 12
        out = F.relu(out)
        out = self.conv5_3(out)  # 14*14*512
        out = F.relu(out)
        # out = self.conv5_4(out)  # 14*14*512
        # out = F.relu(out)
        out5 = self.maxpool5(out)  #7*7*512

        x2=self.encon1(out2)
        x3=self.encon2(out3)
        x4 = self.encon3(out4)

        x=self.ASPP(out5)

        x=self.Debl4(x)
        x = self.Debl3(x+x4)
        x = self.Debl2(x+x3)
        x=self.decov1(x+x2)
        x=self.conv2(x)
        x=self.decov2(x)
        return x

# vgg=VGG16()